package com.wu.http.server;


import com.wu.javax.servlet.Servlet;
import com.wu.javax.servlet.ServletContext;
import com.wu.javax.servlet.ServletRequest;
import com.wu.javax.servlet.ServletResponse;
import com.wu.javax.servlet.http.HttpServlet;
import com.wu.javax.servlet.http.HttpServletRequest;
import com.wu.javax.servlet.http.HttpServletResponse;
import com.wu.util.PackageScan;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 动态资源处理器
 */
public class DynamicProcessor implements Processor {


    @Override
    public void process(ServletRequest request, ServletResponse response) {
        try {
            //获取所有的 类 - 请求路径
            Map<String, List<String>> requestPaths = PackageScan.getRequestPaths();
            // 1 取出URI    /ROOT/hello
            String uri = ((HttpServletRequest) request).getRequestURI();
            //取出请求路径
            String requestPath = uri.substring(uri.replaceFirst("/", "").indexOf("/") + 1);
            Servlet servlet = null;
            //从application中判断是否有这个servletName
            ServletContext application = MyServletContext.getInstance();
            synchronized (this) {
                // 2. 动态字节码加载
                for (Map.Entry<String, List<String>> entry : requestPaths.entrySet()) {
                    String servletName = entry.getKey();
                    List<String> value = entry.getValue();
                    for (String va : value) {
                        if (requestPath.equals(va)) {
                            if (application.getServlet(servletName) != null) {
                                servlet = application.getServlet(servletName);
                            } else {
                                Class<?> aClass = Class.forName(servletName);
                                servlet = (Servlet) aClass.newInstance();
                                application.setServlet(servletName, servlet);
                                servlet.init();
                            }
                        }
                    }
                }
                if (servlet != null) {
                    // 6. 再以生命周期的方式 来调用servlet中的各方法
                    ((HttpServlet) servlet).service((HttpServletRequest) request, (HttpServletResponse) response);
                }
            }
        } catch (Exception e) {
            String bodyEntity = e.getMessage();
            String protocol = gen500(bodyEntity.getBytes().length);
            PrintWriter pw = response.getWriter();
            pw.println(protocol);
            pw.flush();
            pw.println(bodyEntity);
            pw.flush();
        }
    }

    private String gen500(long bodyLength) {
        return "HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: "
                + bodyLength + "\r\n\r\n";
    }
}
